import React from 'react';
import PropTypes from 'prop-types';
import './index.scss';
import SearchItem from './search_item';
// 请求函数
import getArcList from '../../../request/get_arc_list';
import LoadingMore from '../../../components/loading_more/index';

class SearchList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      searchList: [],
      totalCount: 0,
      page: 1,
      perPage: this.props.perPage,
      more: false,
      loading: false,
    }
    this.getMoreSearch = this.getMoreSearch.bind(this)
  }
  componentDidMount() {
    this.onLoadList();
  }
  //
  componentDidUpdate(preProp) {
    if (this.props.keyword !== preProp.keyword) {
      this.onLoadList();
    }
  }
  // 页面第一次加载时请求的函数
  onLoadList() {
    this.getListKeLi(1).then((result) => {
      const res = result.data
      this.setState({
        searchList: res,
        loading: false,
        more: !(res.length < this.state.perPage),
      })
    })
  }
  // 请求文章列表，返回一个Promise
  getList(page, perPage, kerword) {
    this.setState({
      loading: true,
    })
    const params = {
      page,
      per_page: perPage || 10,
      search: decodeURIComponent(kerword),
      categories_exclude: 6,
    }
    const result = getArcList(params);
    return result;
  }

  // 柯里化请求文章列表，减少参数
  getListKeLi(page) {
    const res = this.getList(page, this.state.perPage, this.props.keyword);
    return res;
  }

  // 获取更多搜索结果
  getMoreSearch() {
    this.getListKeLi(this.state.page + 1).then((result) => {
      const res = result.data
      // res.message不存在
      if (!res.message) {
        this.setState({
          searchList: this.state.searchList.concat(res),
          loading: false,
          page: this.state.page + 1,
          more: !(res.length < this.state.perPage),
        })
      } else {
        this.setState({
          loading: false,
          more: false,
        })
      }
    }).catch((e) => {
      console.log(e); //eslint-disable-line
    })
  }
  render() {
    const data = this.state.searchList;
    return (
      <div className="search-list">
        {!data.length ?
          '' :
          data.map((item, index) => (
            <SearchItem data={item} key={item.id} number={index + 1} />
          ))
        }
        <LoadingMore
          isLoading={this.state.loading}
          hasMore={this.state.more}
          getMore={this.getMoreSearch}
        />
      </div>
    )
  }
}
export default SearchList;
SearchList.propTypes = {
  perPage: PropTypes.number,
  keyword: PropTypes.string,
}
